﻿using System;

using System.ComponentModel;
using System.Diagnostics;
using System.Text;
using System.Windows.Forms;

namespace P2P_Backup.forms.controls
{
    public class FolderNode : TreeNode
    {
        archive.Folder folder;
        public FolderNode(archive.Folder folder)
        {           
            this.folder = folder;   
            addFolder(folder, this);
            this.Text = folder.Name;
            this.Name = folder.Name;
            folder.FolderAdded += new EventHandler<archive.FolderArgs>(folder_FolderAdded);
            folder.FileAdded += new EventHandler<archive.FileArgs>(folder_FileAdded);
            folder.FolderRemoved += new EventHandler<archive.FolderArgs>(folder_FolderRemoved);
            folder.FileRemoved += new EventHandler<archive.FileArgs>(folder_FileRemoved);
        }
        
        public FolderNode(String text)
        {
            this.Text = text;
            this.Name = text;
        }
        public archive.Folder getFolder()
        {
            return folder;
        }
        private void folder_FileAdded(object sender, archive.FileArgs e)
        {
            if (this.TreeView.InvokeRequired) this.TreeView.BeginInvoke((MethodInvoker)delegate { folder_FileAdded(sender, e); });
            else
            {
                Nodes.Add(new FileNode(e.File));
                this.Expand();
            }
        }

        private void folder_FolderAdded(object sender, archive.FolderArgs e)
        {
            FolderNode f = new FolderNode(e.Folder);
            Nodes.Add(f);
            this.Expand();
            f.Expand();
        }
        private void folder_FileRemoved(object sender, archive.FileArgs e)
        {
            Nodes.RemoveByKey(e.File.ToString());
        }
        private void folder_FolderRemoved(object sender, archive.FolderArgs e)
        {
            Nodes.RemoveByKey(e.Folder.ToString());
        }
        private void addFolder(archive.Folder folder, FolderNode node)
        {
            foreach (archive.Folder toAdd in folder.Folders)
            {
                node.Nodes.Add(new FolderNode(toAdd));
            }
            foreach (archive.File toAdd in folder.Files)
            {
                node.Nodes.Add(new FileNode(toAdd));
            }
        }
        public override bool Equals(object obj)
        {
            FolderNode node = (FolderNode)obj;
            return this.folder.Equals(node.folder);
        }
        public override int GetHashCode()
        {
            return base.GetHashCode();
        }
    }
}
